import React, { useEffect, useState } from 'react';
import useStore from '../../components/useStore';
import request from '../../untils/request';
import { SearchOutlined, EditOutlined, EyeOutlined } from '@ant-design/icons';
import { notification } from 'antd';

const Customer = () => {
    // 状态管理
    const { collapsed, setnowroute } = useStore();
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize] = useState(10);
    const [total, setTotal] = useState(0);
    const [customers, setCustomers] = useState([]);
    const [searchName, setSearchName] = useState('');

    /**
     * 获取客户列表数据
     * 发送POST请求到后端，携带分页参数和搜索条件
     */
    const fetchCustomers = () => {
        const offset = (currentPage - 1) * pageSize;
        request("/admin/customer/getCustomers", {
            method: "POST",
            body: {
                pageSize,
                offset,
                name: searchName  // 传递查询条件
            }
        }).then((res) => {
            if (res.code === 200) {
                setCustomers(res.data || []);
                setTotal(res.total || 0);
            }
        });
    };

    // 初始加载和页面变化时获取数据
    useEffect(() => {
        fetchCustomers();
    }, [currentPage]);

    /**
     * 处理搜索事件
     * 重置页码为1并重新获取数据
     */
    const handleSearch = () => {
        setCurrentPage(1);  // 搜索时重置到第一页
        fetchCustomers();
    };

    /**
     * 处理回车键搜索
     * @param {Event} e - 键盘事件对象
     */
    const handleKeyPress = (e) => {
        if (e.key === 'Enter') {
            handleSearch();
        }
    };

    /**
     * 处理分页切换
     * @param {number} newPage - 新页码
     */
    const handlePageChange = (newPage) => {
        // 验证页码有效性
        if (newPage < 1 || (total > 0 && newPage > Math.ceil(total / pageSize))) {
            return;
        }
        setCurrentPage(newPage);
    };

    const checkCustomer = () => {
        notification.open({
            message:"当前版本客户信息已在此页面完全展示。"
        })
    }

    const toEdit = (e) => {
        setnowroute({ ...{ route: `/ship/framework/customer/edit?id=${e}`, title: "编辑客户信息" } })
    }

    return (
        <div style={{    
            height: "94%", 
            backgroundColor: `#F1F1F1`,
            right: "1%",
            top: "4vh",
            overflow: "auto",
            width: collapsed ? "94%" : "84%", 
            position: "absolute",  
            color: "white", 
            fontSize: "0.8rem"
        }}>
            <div style={styles.container}>
                {/* 查询区域 */}
                <div style={styles.searchArea}>
                    <h3 style={styles.title}>请输入条件进行查询</h3>
                    <div style={styles.searchFields}>
                        <div style={styles.fieldGroup}>
                            <label style={styles.label}>客户名称：</label>
                            <input
                                type="text"
                                value={searchName}
                                onChange={(e) => setSearchName(e.target.value)}
                                onKeyPress={handleKeyPress}
                                style={styles.input}
                                placeholder="请输入客户名称"
                            />
                        </div>
                        
                        <button 
                            onClick={handleSearch} 
                            style={styles.searchButton}
                        >
                            <SearchOutlined /> 搜索
                        </button>
                    </div>
                </div>

                {/* 按钮区域 */}
                <div style={styles.buttonArea}>
                    <button 
                        onClick={() => setnowroute({
                            route: "/ship/framework/customer/add",
                            title: "新增客户"
                        })} 
                        style={styles.addButton}
                    >
                        新增
                    </button>
                </div>

                {/* 列表区域 */}
                <div style={styles.tableContainer}>
                    <h3 style={styles.title}>客户列表</h3>
                    <table style={styles.table}>
                        <thead>
                            <tr style={styles.tableHeader}>
                                <th style={styles.tableHeaderCell}>序号</th>
                                <th style={styles.tableHeaderCell}>客户名称</th>
                                <th style={styles.tableHeaderCell}>负责人联系方式</th>
                                <th style={styles.tableHeaderCell}>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {customers.length > 0 ? (
                                customers.map((customer, index) => (
                                    <tr 
                                        key={customer.id} 
                                        style={styles.tableRow}
                                        // 增加行悬停效果
                                        onMouseEnter={(e) => {
                                            e.currentTarget.style.backgroundColor = "#f5f5f5";
                                        }}
                                        onMouseLeave={(e) => {
                                            e.currentTarget.style.backgroundColor = "transparent";
                                        }}
                                    >
                                        <td style={styles.tableCell}>
                                            {(currentPage - 1) * pageSize + index + 1}
                                        </td>
                                        <td style={styles.tableCell}>{customer.name}</td>
                                        <td style={styles.tableCell}>{customer.phone || '未填写'}</td>
                                        <td style={styles.tableCell}>
                                            <button style={styles.actionButton} onClick={checkCustomer}>
                                                <EyeOutlined /> 查看
                                            </button>
                                            <button style={styles.actionButton} 
                                                onClick={() => toEdit(customer.id)}>
                                                <EditOutlined /> 修改
                                            </button>
                                        </td>
                                    </tr>
                                ))
                            ) : (
                                <tr>
                                    <td colSpan="4" style={styles.emptyCell}>
                                        暂无数据
                                    </td>
                                </tr>
                            )}
                        </tbody>
                    </table>
                </div>

                {/* 分页区域 */}
                <div style={styles.paginationArea}>
                    <div style={styles.paginationInfo}>
                        共 {total} 条记录
                    </div>
                    <div style={styles.paginationControls}>
                        <button 
                            onClick={() => handlePageChange(currentPage - 1)}
                            disabled={currentPage === 1}
                            style={styles.pageButton}
                        >
                            上一页
                        </button>
                        <span style={styles.currentPage}>{currentPage}</span>
                        <button 
                            onClick={() => handlePageChange(currentPage + 1)}
                            disabled={currentPage >= Math.ceil(total / pageSize) && total > 0}
                            style={styles.pageButton}
                        >
                            下一页
                        </button>
                    </div>
                </div>
            </div>
        </div>
    );
};

export default Customer;

// 样式定义
const styles = {
    container: {
        width: "98%", 
        height: "95%", 
        position: "absolute", 
        top: "3%", 
        left: "1%", 
        backgroundColor: "white", 
        color: "black",
        borderRadius: "10px",
        overflow: "hidden"
    },
    searchArea: {
        padding: "15px 20px",
        borderBottom: "1px solid #eee"
    },
    title: {
        margin: "0 0 15px 0",
        fontSize: "0.9rem",
        color: "#333"
    },
    searchFields: {
        display: "flex",
        alignItems: "center",
        gap: "15px"
    },
    fieldGroup: {
        display: "flex",
        alignItems: "center"
    },
    label: {
        fontSize: "0.8rem",
        marginRight: "5px",
        color: "#666"
    },
    input: {
        padding: "6px 10px",
        border: "1px solid #ddd",
        borderRadius: "4px",
        fontSize: "0.8rem",
        width: "200px"
    },
    searchButton: {
        backgroundColor: "#1890ff",
        color: "white",
        border: "none",
        borderRadius: "4px",
        padding: "6px 12px",
        cursor: "pointer",
        fontSize: "0.8rem",
        display: "flex",
        alignItems: "center",
        gap: "5px",
        transition: "background-color 0.2s"
    },
    buttonArea: {
        padding: "10px 20px",
        display: "flex",
        justifyContent: "flex-end",
        borderBottom: "1px solid #eee"
    },
    addButton: {
        backgroundColor: "#52c41a",
        color: "white",
        border: "none",
        borderRadius: "4px",
        padding: "6px 12px",
        cursor: "pointer",
        fontSize: "0.8rem",
        transition: "background-color 0.2s"
    },
    tableContainer: {
        padding: "15px 20px",
        height: "calc(100% - 210px)",
        overflow: "auto"
    },
    table: {
        width: "100%",
        borderCollapse: "collapse",
        fontSize: "0.8rem"
    },
    tableHeader: {
        backgroundColor: "#1890ff",
        color: "white"
    },
    tableHeaderCell: {
        padding: "10px",
        textAlign: "left",
        border: "1px solid #eee"
    },
    tableRow: {
        borderBottom: "1px solid #eee",
        transition: "background-color 0.2s"
    },
    tableCell: {
        padding: "10px",
        border: "1px solid #eee"
    },
    emptyCell: {
        padding: "40px",
        textAlign: "center",
        color: "#999"
    },
    actionButton: {
        background: "none",
        border: "none",
        color: "#1890ff",
        cursor: "pointer",
        marginRight: "10px",
        display: "inline-flex",
        alignItems: "center",
        gap: "3px",
        fontSize: "0.8rem",
        transition: "color 0.2s"
    },
    paginationArea: {
        padding: "10px 20px",
        display: "flex",
        justifyContent: "space-between",
        alignItems: "center",
        borderTop: "1px solid #eee",
        fontSize: "0.8rem"
    },
    paginationInfo: {
        color: "#666"
    },
    paginationControls: {
        display: "flex",
        alignItems: "center",
        gap: "10px"
    },
    pageButton: {
        padding: "4px 10px",
        border: "1px solid #ddd",
        backgroundColor: "white",
        cursor: "pointer",
        borderRadius: "4px",
        fontSize: "0.8rem",
        transition: "all 0.2s"
    },
    currentPage: {
        padding: "4px 10px",
        border: "1px solid #1890ff",
        backgroundColor: "#1890ff",
        color: "white",
        borderRadius: "4px"
    }
};
